package com.wen.system.service.impl;

import com.wen.common.enums.CodeEnum;
import com.wen.common.utils.ResponseResult;
import com.wen.system.service.SysConfService;
import com.wen.common.enums.ServiceEnum;
import com.wen.common.pojo.system.SysService;
import com.wen.common.utils.ShellCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * @author liwen <devinlive@163.com>
 * @version 1.0
 * @since 2022/12/16 21:29
 */
@Service
public class SysConfServiceImpl implements SysConfService {

    private static final Logger log = LoggerFactory.getLogger(SysConfServiceImpl.class);


    @Bean
    public CommandLineRunner commandLineRunner(){
        return args -> log.info("CommandLineRunners commandLineRunner");
    }

    @Override
    public List<SysService> serviceList() throws Exception {
        List<SysService> result = new ArrayList<>();

        ServiceEnum[] services = ServiceEnum.values();
        log.info("services---------->:{},length {}", services, services.length);
        for (ServiceEnum service : services) {
            String serviceName = service.getServiceName();
            String status = this.queryStatusByName(serviceName);

            SysService sysService = new SysService();
            sysService.setTitle(service.getTitle());
            sysService.setServiceName(serviceName);
            if ("restart".equals(service.getState())) {
                sysService.setState(service.getState());
            } else {
                sysService.setState(status);
            }
            sysService.setDaemon(service.getDaemon());
            result.add(sysService);
            log.info("service result----------> : {}", result.toString());
        }
        return result;
    }

    /**
     * 获取服务运行状态
     *
     * @param serviceName
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    protected String queryStatusByName(String serviceName) throws IOException, InterruptedException {
        String[] cmd = ShellCommand.getSystemctlCmd("status", serviceName);
        ShellCommand.ExecResult execReturn = ShellCommand.exec(cmd);
        return execReturn.exitCode == 3 ? "stop" : "start";
    }

    /**
     * 修改服务状态
     *
     * @param serviceName
     * @param state
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult<?> modServiceStatus(String serviceName, String state) throws Exception {
        String[] cmd;
        ShellCommand.ExecResult result;

        if ("".equals(serviceName) || null == serviceName) {
            return ResponseResult.error(CodeEnum.EC_GEN_INTERNAL);
        }
        // init
        ResponseResult<?> daemonResp = this.serviceDaemon(serviceName);
        if (daemonResp != null) return daemonResp;

        //start|stop|restart
        cmd = ShellCommand.getSystemctlCmd(serviceName, state);
        result = ShellCommand.exec(cmd);
        if (result.exitCode != 0) {
            return ResponseResult.error(CodeEnum.EC_GEN_INTERNAL);
        }
        return ResponseResult.success();
    }

    /**
     * 设置服务是否自启动
     *
     * @param serviceName
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    protected ResponseResult<?> serviceDaemon(String serviceName) throws IOException, InterruptedException {
        ServiceEnum instance = ServiceEnum.getInstance(serviceName);
        if (instance == null) {
            return ResponseResult.error(CodeEnum.EC_GEN_INTERNAL);
        }
        String[] cmd;
        ShellCommand.ExecResult result;
        //enable|disable
        cmd = ShellCommand.getSystemctlCmd(serviceName, instance.getDaemon());
        result = ShellCommand.exec(cmd);
        if (result.exitCode != 0) {
            return ResponseResult.error(CodeEnum.EC_GEN_INTERNAL);
        }
        return null;
    }
}
